package com.app.adnroid.sichuanxiaoke.cn.xiaokebusiness.Utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import static android.graphics.Bitmap.CompressFormat.PNG;

/**
 * Created by Zhangyue on 2017/6/7.
 */

public class BitmapUtils {



    /**
     * @param bitmap     保存的Bitmap
     */
    public static File savePhotoCache( final Bitmap bitmap) {
        if (bitmap == null)
            return null;
        File file = new File(Environment.getExternalStorageDirectory(), "userhead.png");
        if (file.exists()) {
            file.delete();
        }
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileOutputStream output = null;
        try {
            output =new FileOutputStream(file);
            bitmap.compress(PNG, 100, output);
            return file;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (output != null)
                try {
                    output.close();
                } catch (IOException e) {
                    // Ignored
                }
        }
        return null;
    }
    public  static File savaiamge(Bitmap bitmap,Activity activity){
        File file = new File(Environment.getExternalStorageDirectory(), "userhead.png");
        if(file.exists()){
            file.delete();
        }

        FileOutputStream outputStream=null;
        try {
            file.createNewFile();
            outputStream=new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG,100,outputStream);
            return file;
        } catch (IOException e) {
            Log.e("Saveerror","------"+e.getMessage());
            new AlertDialog.Builder(activity)
                    .setTitle("警告")
                    .setMessage("请手动在应用中心打开该应用的读写权限")
                    .setNegativeButton("确定",null)
                    .create()
                    .show();

        }finally {
            if(outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return null;
    }

    /**
     * 从文件获取Bitmap图。（只对avatar头像）
     * @return
     */
    public static Bitmap getPhotoCache() {
        File imageDir = new File(Environment.getExternalStorageDirectory(), "images/avatar");
        if (!imageDir.isDirectory()) {
            imageDir.mkdirs();
        }

        //File imageFile = new File(imageDir, resourceId);

        if (!imageDir.exists() || imageDir.length() == 0)
            return null;

        Bitmap bitmap = BitmapFactory.decodeFile(imageDir.getAbsolutePath());
        if (bitmap != null){
            return bitmap;
        }
        else {
            imageDir.delete();
            return null;
        }
    }

    public static Bitmap scaleDownBitmap(Bitmap photo, int newHeight, Context context) {
        final float densityMultiplier = context.getResources().getDisplayMetrics().density;
        int h = (int) (newHeight * densityMultiplier);
        int w = (int) (h * photo.getWidth() / ((double) photo.getHeight()));
        photo = Bitmap.createScaledBitmap(photo, w, h, true);
        return photo;
    }

    /**
     * 该方法是用来保存截图的Bitmap的，该方法只能截到状态栏下面的，无法截到状态栏
     * @param activity
     * @return 返回的是bitmap的存储路径
     */

    public static String SavePhoneScreenshot(Activity activity){
        //创建Bitmap
        WindowManager windowManager = activity.getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        int width = display.getWidth();
        int height = display.getHeight();
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        //获取屏幕
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        bitmap=view.getDrawingCache();

        File file = new File(Environment.getExternalStorageDirectory(),"/images/sharedimage.jpg");
        String savepath = Environment.getExternalStorageDirectory() + "/images/sharedimage.jpg";
        if(file.exists()){
            file.delete();
        }
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileOutputStream fileOutputStream=null;
        try {
            fileOutputStream = new FileOutputStream(file);
            bitmap.compress(PNG,100,fileOutputStream);
            Log.i("SavePhoneScreenshot","成功保存至："+savepath);
            return savepath;

        } catch (FileNotFoundException e) {
           Log.e("SavePhoneScreenshot","SavePhoneScreenshot is wrong  "+e);
        }finally {
            if(fileOutputStream !=null){
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    //
                }
            }
        }
        return null;


    }

    public static byte[] getBitmapToByte(Bitmap bitmap){
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG,100,outputStream);
        return outputStream.toByteArray();
    }
    public static synchronized Bitmap compressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while ( baos.toByteArray().length / 1024>250) { //循环判断如果压缩后图片是否大于200kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            Log.i("bitmapString","---bitmap 正在压缩----");
            options -= 10;//每次都减少10
        }
        Log.i("bitmapString","-------压缩完成");
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
        //把ByteArrayInputStream数据生成图片
        //如果没有回收  则回收
        if(!image.isRecycled()){
            image.recycle();
        }
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
        return bitmap;
    }
}
